package com.satan.juc.demo14;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class InventoryManager {
    // 使用ConcurrentHashMap来存储商品的库存数量
    private ConcurrentHashMap<String, Integer> inventory = new ConcurrentHashMap<>();

    public InventoryManager() {
        // 初始化库存
        inventory.put("手机", 100);
        inventory.put("平板", 50);
    }

    // 增加库存
    public void addStock(String item, int quantity) {
        inventory.compute(item, (key, val) -> (val == null) ? quantity : val + quantity);
    }

    // 减少库存
    public void deductStock(String item, int quantity) {
        inventory.computeIfPresent(item, (key, val) -> (val < quantity) ? 0 : val - quantity);
    }

    // 获取库存数量
    public int getStock(String item) {
        return inventory.getOrDefault(item, 0);
    }

    public static void main(String[] args) throws InterruptedException {
        InventoryManager manager = new InventoryManager();

        // 创建一个固定大小的线程池来模拟高并发环境
        ExecutorService service = Executors.newFixedThreadPool(10);

        // 模拟多个用户同时修改库存
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            service.submit(() -> {
                if (finalI % 2 == 0) {
                    manager.addStock("手机", 1);
                } else {
                    manager.deductStock("手机", 1);
                }
            });
        }

        // 关闭线程池
        service.shutdown();
        service.awaitTermination(1, TimeUnit.MINUTES);

        // 打印最终的库存数量
        System.out.println("最终手机库存数量: " + manager.getStock("手机"));
    }
}
